from djoser.serializers import UserCreateSerializer
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from django.contrib.auth.models import User

#自定义错误信息
#CustomUniqueValidator需要错误信息中带参数，自定义名称
#UniqueValidator需要错误信息不需要带参数，固定写法

class CustomUniqueValidator(UniqueValidator):
        def __call__(self, value,serializer_field):
            self.message = self.message % {'value': value}
            super().__call__(value, serializer_field)

class AccountCreateSerializer(UserCreateSerializer):
    email = serializers.EmailField(
        validators=[
            CustomUniqueValidator(
                queryset=User.objects.all(),
                message='邮箱 %(value)s 已经存在'
            )
        ]
    )

    class Meta:
        model = User
        fields = ('id','username', 'email', 'password')